#include<iostream>
#include<string>
#include<string.h>
#include<cstdio>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<stdlib.h>
using namespace std;
class Sock
{
public:
  static int Socket()
  {
    int sock = socket(AF_INET,SOCK_STREAM,0);
    if(sock < 0)
    {
      perror("socket");
      exit(1);
    }
    return sock;
  }
  static void Bind(int sock,uint16_t port) //要绑定哪个套接字 端口号
  {
    struct sockaddr_in local;
    socklen_t len = sizeof(local);
    memset(&local,0,len);
    local.sin_family = AF_INET;
    local.sin_port = htons(port); // 主机字节序 -> 网络字节序
    local.sin_addr.s_addr = INADDR_ANY;
    if(bind(sock,(struct sockaddr*)&local,len) < 0)
    {
      perror("bind");
      exit(2);
    }
  }
  static void Listen(int sock)
  {
    if(listen(sock,5) < 0)
    {
      perror("listen");
      exit(3);
    }
  }
  static void Connect(int sock,string ip,uint16_t port)
  {
   struct sockaddr_in server; 
   socklen_t len = sizeof(server);
   memset(&server,0,len);
   server.sin_family = AF_INET;
   server.sin_port = htons(port); 
   server.sin_addr.s_addr = inet_addr(ip.c_str());//字符串ip->整数ip 整数ip才是网络传输时采用的格式
   if(connect(sock,(struct sockaddr*)&server,len) < 0)
   {
     perror("connect");
     exit(4);
   }
  }
  static int Accept(int sock)
  {
    struct sockaddr_in peer;
    memset(&peer,0,sizeof(peer));
    socklen_t len = sizeof(peer); 
    int new_sock = accept(sock,(struct sockaddr*)&peer,&len);
    if(new_sock >= 0)
    {
        //输出是谁发起的链接
        string ip = inet_ntoa(peer.sin_addr);
        uint16_t port = ntohs(peer.sin_family);
        
        cout <<"peer ip:" << ip <<" " <<"port :" << port << endl;
         return new_sock;
    }
    return -1;
  }
};
